#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <set>
#include <pthread.h>
#include "InterAddr.hpp"
#include "ThreadPool.hpp"
#include "LockGuard.hpp"
using task_t = std::function<void()>;
class MessageRoute
{
private:
    bool IsExists(const InterAddr &addr)
    {
        for (auto a : _online_user)
        {
            if (a == addr)
                return true;
        }
        return false;
    }
public:
    MessageRoute()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }
    void AddUser(const InterAddr &addr)
    {
        LockGuard lock(&_mutex);
        if (IsExists(addr)) return;
        _online_user.push_back(addr); 
    }
    void DelUser(const InterAddr &addr)
    {
        LockGuard lock(&_mutex);
        for (auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
            if (*iter == addr)
            {
                _online_user.erase(iter);
                break;
            }
        }
    }

    void RouteHelper(int sockfd, const std::string message, InterAddr who)
    {
        // 加锁保护
        LockGuard lock(&_mutex);
        // 2. 消息转发
        //这有点问题
        for (auto user : _online_user)
        {
            std::string send_message = "[" + who.Ip() + std::to_string(who.Port()) + "]# " + message + "\n"; 
            struct sockaddr_in clinetaddr = user.Addr();
            ::sendto(sockfd, send_message.c_str(), send_message.size(), 0, (const struct sockaddr*)(&clinetaddr), sizeof(clinetaddr));
        }
    }

    void Route(int sockfd, const std::string message,const InterAddr who)
    {
        //1. 我们的任务，用户首次发消息，不光是发个消息，还要将自己插入在线用户
        AddUser(who);

        // 1.1 如果客户端想要退出
        if (message == "Q" || message == "QUIT")
        {
            DelUser(who);
        }

        //2. 构建任务对象，入队列，让线程池进行转发
        task_t t = std::bind(&MessageRoute::RouteHelper, this, sockfd, message, who);
        ThreadPool<task_t>::GetINstance()->Enqueue(t);

        
    }
    ~MessageRoute()
    {
        pthread_mutex_destroy(&_mutex);
    }
private:
    std::vector<InterAddr> _online_user;//这里是多线程添加/查找/删除，需要加锁保护
    //TODO
    pthread_mutex_t _mutex;
};